﻿package
{
	import org.flixel.FlxSprite;
	import org.flixel.FlxG;
	import org.flixel.FlxSound;
	import ASF;
	
	public class ASUFO extends FlxSprite
	{
		[Embed(source = 'data/UFO.png')] private var imgUFO:Class;
		[Embed(source = 'data/ufo_blast.mp3')] private var sndUFOBlast:Class;
		[Embed(source = 'data/ufo_loop.mp3')] private var sndUFOLoop:Class;
		
		private var _direction:int;
		private var _parent:StateGameLoop;
		private var _snd_looped:FlxSound;
		private var _snd_blast:FlxSound;
		
		public function ASUFO(ParentState:StateGameLoop)
		{
			super();
			width = 32;
			height = 12;
			_parent = ParentState;
			loadGraphic(imgUFO, true, false, width, height, false);
			addAnimation("ufo", [0,1,2,3], 6, true);
			play("ufo");
			
			_snd_looped = new FlxSound();
			_snd_blast = new FlxSound();
			
			_snd_looped.loadEmbedded(sndUFOLoop, true);
			_snd_blast.loadEmbedded(sndUFOBlast);
			
			exists = false;
			visible = false;
			_direction = 0;
		}
		
		public function spawn():void
		{
			_direction = int(FlxG.random() * 2) ? LEFT : RIGHT;
			if (_direction == LEFT) {
				x = -width;
				velocity.x = ASF.UFO_SPEED;
			} else {
				x = FlxG.width;
				velocity.x = -ASF.UFO_SPEED;
			}
			
			y = Utils.randRange(0, ASF.UFO_MAX_Y);
			exists = true;
			visible = true;
			dead = false;
			
			_snd_looped.play();
		}
		
		override public function update():void
		{
			// Move...
			
			if (_direction == LEFT) {
				if (x > (FlxG.width)) {
					hurt(1);
				}
			}
			else {
				if (x <= -width) {
					hurt(1);
				}
			}
			// Shoot occasionally
			
			var shot:ASUFOShot = FlxG.getNonexist( _parent._ufoShots ) as ASUFOShot;
			if (shot) {
				shot.spawn(x + (width / 2), y + (height / 2), _parent._player.x + 8, _parent._player.y + 8);
				_snd_blast.play();
			}
			
			super.update();
		}
		
		override public function hurt(Damage:Number):void
		{
			visible = false;
			exists = false;
			dead = true;
			super.hurt(Damage);
			_snd_looped.stop();
		}
				
		public function getScore():uint
		{
			return ASF.SCORE_UFO;
		}
	}
}